package com.skanda.common.util;

import com.skanda.common.Constants.CommonConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;

public class WebUtil {
    public static String getUserId()
    {
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Object userIdObject = request.getAttribute("userId");
        if(userIdObject!=null){
            return null;
        }
        String headerToken = request.getHeader(CommonConstant.AUTH_KEY); //.getFirst(CommonConstant.AUTH_KEY);
        if (!StringUtils.hasText(headerToken) ) {
            return null;
        }
        Claims claims = null;
        try {
            claims = Jwts.parserBuilder()
                    .setSigningKey(CommonConstant.SIGN_KEY.getBytes(Charset.forName("UTF-8"))).build()
                    .parseClaimsJws(headerToken).getBody();
        }catch (Exception e){
            return null;
        }
        if (claims == null || claims.get("user_id")==null) {
            return null;
        }
        return  (String) claims.get("user_id");
    }
    public static String getUserRoleName()
    {
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Object userIdObject = request.getAttribute("userId");
        if(userIdObject!=null){
            return null;
        }
        String headerToken = request.getHeader(CommonConstant.AUTH_KEY); //.getFirst(CommonConstant.AUTH_KEY);
        if (!StringUtils.hasText(headerToken) ) {
            return null;
        }
        Claims claims = null;
        try {
            claims = Jwts.parserBuilder()
                    .setSigningKey(CommonConstant.SIGN_KEY.getBytes(Charset.forName("UTF-8"))).build()
                    .parseClaimsJws(headerToken).getBody();
        }catch (Exception e){
            return null;
        }
        if (claims == null || claims.get("role_name")==null) {
            return null;
        }
        return  (String) claims.get("role_name");
    }
}
